package com.ly.oa.web.action;

import com.ly.oa.utils.DBUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

// 模板类
@WebServlet({"/dept/list", "/dept/add", "/dept/edit", "/dept/detail", "/dept/delete", "/dept/modify"})
// 模糊匹配
// 只要请求路径是以"/dept"开始的，都走这个Servlet。oa2.iml
//@WebServlet("/dept/*")
public class DeptServlet extends HttpServlet {
    //    模板方法
//    重写service方法（并没有重写doGet或者doPost）
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        获取servlet path
        String servletPath = request.getServletPath();
        if ("/dept/list".equals(servletPath)) {
            doList(request, response);
        } else if ("/dept/add".equals(servletPath)) {
            doAdd(request, response);
        } else if ("/dept/edit".equals(servletPath)) {
            doEdit(request, response);
        } else if ("/dept/detail".equals(servletPath)) {
            doDetail(request, response);
        } else if ("/dept/delete".equals(servletPath)) {
            doDel(request, response);
        } else if ("/dept/modify".equals(servletPath)) {
            doModify(request, response);
        }
    }

    private void doList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //        获取应用的根路径
        String contextPath = request.getContextPath();

//        设置响应的内容类型以及字符集，防止中文乱码问题
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        out.print("<!DOCTYPE html>");
        out.print("<html>");
        out.print("	<head>");
        out.print("		<meta charset='utf-8'>");
        out.print("		<title>部门列表页面</title>");
        out.print("	</head>");
        out.print("	<body>");
        out.print("<script type='text/javascript'>");
        out.print("        function del(dno) {");
        out.print("    if(window.confirm('亲，删了不可恢复哦！！！')){");
        out.print("        document.location.href = '" + contextPath + "/dept/delete?deptno=' + dno;");
        out.print("    }");
        out.print("}");
        out.print("</script>");
        out.print("		<h1 align='center'>部门列表</h1>");
        out.print("		<hr>");
        out.print("		<table border='1px' align='center' width='50%'>");
        out.print("			<tr>");
        out.print("				<th>序号</th>");
        out.print("				<th>部门编号</th>");
        out.print("				<th>部门名称</th>");
        out.print("				<th>操作</th>");
        out.print("			</tr>");
//out.print("			<!-- 以上是固定的 -->");

//        jdbc连接数据库,查询所有的部门
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
//        获取连接
            conn = DBUtil.getConnection();
//        获取预编译的数据库操作对象
            String sql = "SELECT deptno AS a,dname,loc FROM dept";
            ps = conn.prepareStatement(sql);
//        执行sql语句
            rs = ps.executeQuery();
//        处理结果集
            int i = 0;
            while (rs.next()) {
                String deptno = rs.getString("a");
                String dname = rs.getString("dname");
                String loc = rs.getString("loc");

//out.print("			<!-- 以下是动态的 -->");
                out.print("			<tr>");
                out.print("				<td>" + (++i) + "</td>");
                out.print("				<td>" + deptno + "</td>");
                out.print("				<td>" + dname + "</td>");
                out.print("				<td>");
                out.print("					<a href='javascript:void(0)' onclick='del(" + deptno + ")'>删除</a>");
                out.print("					<a href='" + contextPath + "/dept/edit?deptno=" + deptno + "'>修改</a>");
                out.print("					<a href='" + contextPath + "/dept/detail?deptno=" + deptno + "'>详情</a>");
                out.print("				</td>");
                out.print("			</tr>");
            }

        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
//        释放资源
            DBUtil.close(conn, ps, rs);
        }
        //out.print("			<!-- 以下是固定的 -->");
        out.print("			<tr>");
        out.print("				<td colspan='4' align='center'><a href='" + contextPath + "/add.html'>新增部门</a></td>");
        out.print("			</tr>");
        out.print("		</table>");
        out.print("	</body>");
        out.print("</html>");
    }

    private void doAdd(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String deptno = request.getParameter("deptno");
        String dname = request.getParameter("dname");
        String loc = request.getParameter("loc");

        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        int count = 0;

        try {
            conn = DBUtil.getConnection();
            String sql = "INSERT INTO dept VALUES (?,?,?)";
            ps = conn.prepareStatement(sql);
            ps.setString(1, deptno);
            ps.setString(2, dname);
            ps.setString(3, loc);
            count = ps.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            DBUtil.close(conn, ps, rs);
        }

        if (count == 1) {
//            转发
//            request.getRequestDispatcher("/dept/list").forward(request,response);
//            重定向
            response.sendRedirect(request.getContextPath() + "/dept/list");
        } else {
//            转发
//            request.getRequestDispatcher("/error.html").forward(request, response);
//            重定向
            response.sendRedirect(request.getContextPath() + "/error.html");
        }
    }

    private void doEdit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String contextPath = request.getContextPath();
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        out.print("<!DOCTYPE html>");
        out.print("<html>");
        out.print("	<head>");
        out.print("		<meta charset='utf-8'>");
        out.print("		<title>修改页面</title>");
        out.print("	</head>");
        out.print("	<body>");
        out.print("		<h1 align='center'>修改部门信息</h1>");
        out.print("		<hr>");
        out.print("		<form action='" + contextPath + "/dept/modify' align='center' method='post'>");

        String deptno = request.getParameter("deptno");

        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;

        try {
            conn = DBUtil.getConnection();
            String sql = "SELECT * FROM dept WHERE deptno = ?";
            ps = conn.prepareStatement(sql);
            ps.setString(1, deptno);
            rs = ps.executeQuery();
            if (rs.next()) {
                deptno = rs.getString("deptno");
                String dname = rs.getString("dname");
                String loc = rs.getString("loc");
                out.print("                部门编号<input type='text' name='deptno' value='" + deptno + "' readonly/><br>");
                out.print("                部门名称<input type='text' name='dname' value='" + dname + "'/><br>");
                out.print("                部门位置<input type='text' name='loc' value='" + loc + "'/><br>");
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            DBUtil.close(conn, ps, rs);
        }

        out.print("			<input type='submit' value='修改'/><br>");
        out.print("		</form>");
        out.print("	</body>");
        out.print("</html>");
    }

    private void doDetail(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        out.print("<!DOCTYPE html>");
        out.print("<html>");
        out.print("	<head>");
        out.print("		<meta charset='utf - 8'>");
        out.print("		<title>详情页面</title>");
        out.print("	</head>");
        out.print("	<body>");
        out.print("		<h1 align='center'>部门详细信息</h1>");
        out.print("		<hr>");
        out.print("		<table border='1px' align='center' width='40%'>");

//        获取部门编号
//        /oa/dept/detail?deptno=30
//        虽然是提交的30，但服务器获取的是“30”这个字符串
        String deptno = request.getParameter("deptno");

//        连接数据库，根据部门编号查询部门信息
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;

        try {
            conn = DBUtil.getConnection();
            String sql = "SELECT dname,loc FROM dept WHERE deptno = ?";
            ps = conn.prepareStatement(sql);
            ps.setString(1, deptno);
            rs = ps.executeQuery();
            if (rs.next()) {
                String dname = rs.getString("dname");
                String loc = rs.getString("loc");
                out.print("			<tr>");
                out.print("				<th>部门编号</th>");
                out.print("				<td align='center'>" + deptno + "</td>");
                out.print("			</tr>");
                out.print("			<tr>");
                out.print("				<th>部门名称</th>");
                out.print("				<td align='center'>" + dname + "</td>");
                out.print("			</tr>");
                out.print("			<tr>");
                out.print("				<th>部门位置</th>");
                out.print("				<td align='center'>" + loc + "</td>");
                out.print("			</tr>");
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            DBUtil.close(conn, ps, rs);
        }
        out.print("			<tr>");
        out.print("				<td colspan='2' align='center'><input type='button' value='返回' onclick='window.history.back()'/></td>");
        out.print("			</tr>");
        out.print("		</table>");
        out.print("	</body>");
        out.print("</html>");
    }

    private void doDel(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();

        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;

        String deptno = request.getParameter("deptno");
        int count = 0;

        try {
            conn = DBUtil.getConnection();
//            开启事务（自动提交事务关闭）
            conn.setAutoCommit(false);
            String sql = "DELETE FROM dept WHERE deptno = ?";
            ps = conn.prepareStatement(sql);
            ps.setString(1, deptno);
            count = ps.executeUpdate();
//            事务提交
            conn.commit();
        } catch (SQLException e) {
//            遇到异常需要回滚
            if (conn != null) {
                try {
                    conn.rollback();
                } catch (SQLException ex) {
                    throw new RuntimeException(ex);
                }
            }
            throw new RuntimeException(e);
        } finally {
            DBUtil.close(conn, ps, rs);
        }

        if (count == 1) {
//            删除成功，仍然跳转到部门列表页面
//            request.getRequestDispatcher("/dept/list").forward(request,response);
            response.sendRedirect(request.getContextPath() + "/dept/list");
        } else {
//            删除失败
//            request.getRequestDispatcher("/error.html").forward(request,response);
            response.sendRedirect(request.getContextPath() + "/error.html");
        }
    }

    private void doModify(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        解决请求体的中文乱码问题
        request.setCharacterEncoding("UTF-8");
//        获取表单中的数据
        String deptno = request.getParameter("deptno");
        String dname = request.getParameter("dname");
        String loc = request.getParameter("loc");

        Connection conn = null;
        PreparedStatement ps = null;

        int count = 0;

        try {
            conn = DBUtil.getConnection();
            String sql = "update dept set dname = ?,loc = ? where deptno = ?";
            ps = conn.prepareStatement(sql);
            ps.setString(1,dname);
            ps.setString(2,loc);
            ps.setString(3,deptno);
            count = ps.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            DBUtil.close(conn,ps,null);
        }

        if (count == 1){
//            request.getRequestDispatcher("/dept/list").forward(request,response);
            response.sendRedirect(request.getContextPath() + "/dept/list");
        }else {
//            request.getRequestDispatcher("/error.html").forward(request,response);
            response.sendRedirect(request.getContextPath() + "/error.html");
        }
    }
}
